var Promise = function (executor) {
  var that = this
  this.executor = executor
  this.status = 'pending'
  this.data = undefined
  this.onResolvedCallbacks = []
  this.onRejectedCallbacks = []

  function resolve (value) {
    if (that.status === 'pending') {
      that.status = 'resolved'
      that.data = value
      for (var i = 0; i < that.onResolvedCallbacks.length; i++) {
        that.onResolvedCallbacks[i](value)
      }
    }
  }

  function reject (reason) {
    if (that.status === 'pending') {
      that.status = 'rejected'
      that.data = reason
      for (var i = 0; i < that.onRejectedCallbacks.length; i++) {
        that.onRejectedCallbacks[i](value)
      }
    }
  }

  // 传入 promise 的函数会直接执行, 在所有的 then 之前执行
  // 这里可能立即会想到 then 在回调成功之后才会执行的问题，
  // 然而这个问题是不存在的，因为每一个 then 被调用的时候，
  // 而且函数的签名是确定的
  try {
    executor(resolve, reject)
  } catch (e) {
    reject(e)
  }
}

Promise.prototype.then = function (onResolved, onRejected) {
  var that = this
  var promise2

  // 保证两个回调必须是函数
  if (typeof onResolved !== 'function') {
    onResolved = function (v) {
    }
  }

  if (typeof onRejected !== 'function') {
    onRejected = function (r) {
    }
  }

  // 标准规定 then 必须返回一个新的 promise 对象
  if (that.status === 'resolved') {
    return promise2 = new Promise(function (resolve, reject) {
      try {
        var x = onResolved(this.data)
        if (x instanceof Promise) {
          x.then(resolve, reject)
        } else {
          resolve(x)
        }
      } catch (e) {
        reject(e)
      }
    })
  }

  if (that.status === 'rejected') {
    return promise2 = new Promise(function (resolve, reject) {
      try {
        var x = onRejected(that.data)
        if (x instanceof Promise) {
          x.then(resolve, reject)
        }
      } catch (e) {
        reject(e)
      }
    })
  }

  if (that.status === 'pending') {
    return promise2 = new Promise(function (resolve, reject) {

      that.onResolvedCallbacks.push(function (value) {
        try {
          var x = onResolved(that.data)
          if (x instanceof Promise) {
            x.then(resolve, reject)
          }
        } catch (e) {
          reject(e)
        }
      })

      that.onRejectedCallbacks.push(function (reason) {
        try {
          var x = onRejected(that.data)
          if (x instanceof Promise) {
            x.then(resolve, reject)
          }
        } catch (e) {
          reject(e)
        }
      })

    })
  }
}

// promise 对象创建的时候会直接执行
// 但是似乎并不影响后续 then 的执行
// 因为 then 中传递的方法, 在 promise 方法没有执行的时候
// 会保存
var pro = new Promise(
  function (succ, fail) {
    console.dir('init')
    succ(1024)
  }
)

pro.then(function () {
  console.dir('then1')
}, function () {
  console.dir('fail')
}).then(function () {
  console.dir('then2')
})
